package com.ymq.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.ymq.reggie.common.BaseContext;
import com.ymq.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "logCheckFilter",urlPatterns = "/*")//
@Slf4j
public class LogCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1=(HttpServletRequest) request;
        HttpServletResponse response1=(HttpServletResponse) response;

        String requestURI = request1.getRequestURI();
        System.out.println(requestURI);
        log.info("本次请求地址:{}",requestURI);

        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
              "/user/sendMsg"
        };
        boolean check = check(urls, requestURI);
        //如果不需要处理直接放行
        if (check){
            log.info("本次请求不需要处理:{}",requestURI);
            chain.doFilter(request1,response1);
            return;

        }
        //店员登录
        if(request1.getSession().getAttribute("employee")!=null){

            Long employeeId = (Long) request1.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(employeeId);
            log.info("ThreadLocal的线程Id:{}",BaseContext.getThreadLocalId());

            log.info("用户已登录:{}",request1.getSession().getAttribute("employee"));
            chain.doFilter(request1,response1);

            return;
        }
        //用户登录
        if(request1.getSession().getAttribute("user")!=null){

            Long userId = (Long) request1.getSession().getAttribute("user");
            BaseContext.setThreadLocal(userId);
            log.info("ThreadLocal的线程Id:{}",BaseContext.getThreadLocalId());

            log.info("用户已登录:{}",request1.getSession().getAttribute("user"));
            chain.doFilter(request1,response1);

            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("本次请求已被拦截");
        return;

    }


    public boolean check(String[] urls,String ur){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, ur);
            if (match){
                return true;
            }

        }return false;
    }


}
